package com.travelDevelop.iterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebFilter(filterName = "TestFilter", urlPatterns = "/*",asyncSupported = true)
public class TestFilter implements Filter {

	@Override
	public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException {
//		HttpServletRequest request = (HttpServletRequest) req;
//		HttpServletResponse response = (HttpServletResponse) res;
//
//		AsyncContext asyncContext = req.startAsync();
//		asyncContext.addListener(new AsyncListener() {
//
//			@Override
//			public void onComplete(AsyncEvent arg0) throws IOException {
//				
//			}
//
//			@Override
//			public void onError(AsyncEvent arg0) throws IOException {
//				// TODO Auto-generated method stub
//
//			}
//
//			@Override
//			public void onStartAsync(AsyncEvent arg0) throws IOException {
//				// TODO Auto-generated method stub
//
//			}
//
//			@Override
//			public void onTimeout(AsyncEvent arg0) throws IOException {
//				// TODO Auto-generated method stub
//
//			}
//		});
//
//		new Thread(new MyThread(asyncContext)).start();
		
		chain.doFilter(req, res);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		System.out.println("过滤器初始化");

	}

	@Override
	public void destroy() {
		System.out.println("过滤器销毁");
	}

	class MyThread implements Runnable {

		private AsyncContext asyncContext;

		public MyThread(AsyncContext asyncContext) {
			this.asyncContext = asyncContext;
		}

		public void run() {
			PrintWriter out = null;
			try {
				try {
					Thread.sleep(10000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				out = asyncContext.getResponse().getWriter();
				out.println("myTask starts:" + new Date() + "<br>");
				out.flush();
				out.print("myTask ends:" + new Date() + "<br>");
				out.flush();
				asyncContext.complete();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

}
